/*
 * Copyright 2011 J. Auer, J. Andert, F.-J. Jendrusch, U. Celebi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.fuberlin.replication.test.library;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import de.fuberlin.replication.library.Subset;
import de.fuberlin.replication.library.Version;
import de.fuberlin.replication.library.VersionVector;
import de.fuberlin.replication.storage.SubsetDAO;

public class SubsetDAODummy implements SubsetDAO {

	public List<Subset> subsets = new ArrayList<Subset>();
	
	public long versionCounter = 0;
	
	@Override
	public Iterable<Subset> getAll() {
		ArrayList<Subset> resultSet = new ArrayList<Subset>();
		
		for(Subset set:subsets)
			resultSet.add(clone(set));
		
		return resultSet;
	}

	@Override
	public Subset create() {
		Subset set = new Subset();
		set.setId(++versionCounter);
		set.setObjectNames(new Vector<String>());
		subsets.add(set);
		
		return set;
	}

	@Override
	public void save(Subset subset) {
		delete(subset);

		if(subset.getId() == 0)
			subset.setId(++versionCounter);
		
		subsets.add(clone(subset));
	}

	@Override
	public void delete(Subset subset) {
		for(int i=0; i<subsets.size(); ++i)
			if(subsets.get(i).getId() == subset.getId()) {
				subsets.remove(i);
				break;
			}
	}

	private static Subset clone(Subset set) {
		Subset clonedSet = new Subset();
		clonedSet.setId(set.getId());
		VersionVector knowledge = new VersionVector();
		
		for(Version v:set.getKnowledge())
			knowledge.add(new Version(v.getReplica(), v.getVersion()));
		
		clonedSet.setKnowledge(knowledge);
		
		Vector<String> clonedNames = new Vector<String>();
		
		for(String s:set.getObjectNames())
			clonedNames.add(s);
		
		clonedSet.setObjectNames(clonedNames);
		
		return clonedSet;
	}
}